<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品详情 - 百货购物平台</title>
    <link rel="stylesheet" href="layui-v2.9.20/layui/css/layui.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="layui-v2.9.20/layui/layui.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Microsoft YaHei", "PingFang SC", sans-serif;
        }

        body {
            background: linear-gradient(135deg, #fff0f3 0%, #ffecef 100%);
            min-height: 100vh;
        }

        /* 顶部导航栏 */
        .header-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: linear-gradient(135deg, #ffecef 0%, #fff0f3 100%);
            padding: 0 40px;
            box-shadow: 0 4px 20px rgba(255, 156, 176, 0.15);
            position: relative;
            z-index: 1000;
            height: 70px;
            border-bottom: 1px solid #ffdde4;
        }

        .logo {
            display: flex;
            align-items: center;
            font-size: 28px;
            font-weight: 800;
            color: #ff4d7a;
            text-shadow: 1px 1px 3px rgba(255, 77, 122, 0.2);
        }

        .logo i {
            margin-right: 10px;
            font-size: 32px;
        }

        .nav-menu {
            display: flex;
            list-style: none;
            height: 100%;
        }

        .nav-menu li {
            display: flex;
            align-items: center;
            position: relative;
            padding: 0 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            height: 100%;
        }

        .nav-menu li a {
            text-decoration: none;
            color: #ff4d7a;
            font-size: 16px;
            font-weight: 600;
            display: flex;
            align-items: center;
            height: 100%;
            padding: 0 5px;
            transition: all 0.3s;
        }

        .nav-menu li a i {
            margin-right: 8px;
            font-size: 18px;
        }

        .nav-menu li:hover {
            background: rgba(255, 255, 255, 0.5);
        }

        .nav-menu li.active {
            background: linear-gradient(to bottom, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0.4));
        }

        .nav-menu li.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(to right, #ff8da1, #ff4d7a);
            border-radius: 3px 3px 0 0;
        }

        .nav-menu li.active a {
            color: #e6004c;
        }

        .user-info {
            display: flex;
            align-items: center;
            margin-left: 20px;
            color: #ff4d7a;
            font-weight: 600;
            cursor: pointer;
        }

        .user-info i {
            margin-right: 8px;
            font-size: 20px;
        }

        /* 商品详情容器 */
        .product-detail-container {
            max-width: 1200px;
            margin: 40px auto;
            padding: 0 20px;
        }

        .detail-content {
            display: flex;
            background: #fff;
            border-radius: 15px;
            box-shadow: 0 15px 40px rgba(255, 141, 161, 0.25);
            overflow: hidden;
        }

        /* 商品图片区域 */
        .product-gallery {
            width: 50%;
            padding: 30px;
            border-right: 1px solid #f0f0f0;
        }

        .main-image-container {
            position: relative;
            overflow: hidden;
            border-radius: 12px;
            background: #fff9fb;
            height: 400px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20px;
        }

        .main-image {
            max-width: 90%;
            max-height: 90%;
            object-fit: contain;
            transition: transform 0.3s;
        }

        .thumbnail-container {
            display: flex;
            gap: 15px;
            justify-content: center;
        }

        .thumbnail {
            width: 80px;
            height: 80px;
            border-radius: 8px;
            border: 2px solid #ffdde4;
            cursor: pointer;
            overflow: hidden;
            transition: all 0.3s;
        }

        .thumbnail img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .thumbnail.active {
            border-color: #ff4d7a;
            transform: scale(1.05);
        }

        .thumbnail:hover {
            border-color: #ff8da1;
        }

        /* 商品信息区域 */
        .product-info {
            width: 50%;
            padding: 30px;
            background: #fff;
        }

        .product-title {
            font-size: 28px;
            color: #333;
            margin-bottom: 15px;
            font-weight: 700;
            line-height: 1.3;
        }

        .product-subtitle {
            color: #888;
            font-size: 16px;
            margin-bottom: 25px;
        }

        .price-container {
            background: #fff9fb;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 25px;
            border: 1px dashed #ffdde4;
        }

        .price-label {
            color: #888;
            font-size: 16px;
            margin-bottom: 8px;
        }

        .current-price {
            font-size: 36px;
            color: #ff4d7a;
            font-weight: 800;
            margin-right: 15px;
        }

        .original-price {
            font-size: 22px;
            color: #999;
            text-decoration: line-through;
        }

        .sales-info {
            display: flex;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px dashed #ffdde4;
        }

        .info-item {
            margin-right: 30px;
            color: #666;
        }

        .info-item span {
            color: #ff4d7a;
            font-weight: 600;
        }

        /* 规格选择 */
        .spec-container {
            margin-bottom: 25px;
        }

        .spec-title {
            font-size: 18px;
            color: #666;
            margin-bottom: 15px;
            font-weight: 600;
        }

        .spec-options {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
        }

        .spec-option {
            padding: 8px 20px;
            border: 1px solid #ffdde4;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s;
            color: #666;
            background: #fff;
        }

        .spec-option:hover {
            border-color: #ff8da1;
        }

        .spec-option.selected {
            background: #ffedf0;
            border-color: #ff4d7a;
            color: #ff4d7a;
            font-weight: 600;
        }

        /* 数量选择 */
        .quantity-container {
            margin-bottom: 30px;
        }

        .quantity-title {
            font-size: 18px;
            color: #666;
            margin-bottom: 15px;
            font-weight: 600;
        }

        .quantity-control {
            display: flex;
            align-items: center;
        }

        .quantity-btn {
            width: 40px;
            height: 40px;
            border: 1px solid #ffdde4;
            background: #fff;
            border-radius: 8px;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            color: #ff4d7a;
            font-size: 20px;
            transition: all 0.2s;
        }

        .quantity-btn:disabled {
            color: #ddd;
            cursor: not-allowed;
        }

        .quantity-btn:hover:not(:disabled) {
            background: #fff9fb;
        }

        .quantity-input {
            width: 70px;
            height: 40px;
            text-align: center;
            border: 1px solid #ffdde4;
            border-radius: 8px;
            margin: 0 10px;
            color: #333;
            font-size: 18px;
            font-weight: 600;
        }

        .stock-info {
            margin-left: 20px;
            color: #666;
        }

        .stock-info span {
            color: #ff4d7a;
            font-weight: 600;
        }

        /* 按钮区域 */
        .action-buttons {
            display: flex;
            gap: 20px;
            margin-top: 30px;
        }

        .cart-btn, .buy-btn {
            flex: 1;
            height: 55px;
            border-radius: 10px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 5px 15px rgba(255, 77, 122, 0.2);
        }

        .cart-btn {
            background: #fff;
            border: 2px solid #ff4d7a;
            color: #ff4d7a;
        }

        .cart-btn:hover {
            background: #fff9fb;
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(255, 77, 122, 0.3);
        }

        .buy-btn {
            background: linear-gradient(135deg, #ff4d7a 0%, #ff8da1 100%);
            color: white;
            border: none;
        }

        .buy-btn:hover {
            background: linear-gradient(135deg, #ff3366 0%, #ff7799 100%);
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(255, 77, 122, 0.4);
        }

        .cart-btn i, .buy-btn i {
            margin-right: 10px;
            font-size: 20px;
        }

        /* 商品详情描述 */
        .product-description {
            margin-top: 40px;
            background: #fff;
            border-radius: 15px;
            box-shadow: 0 15px 40px rgba(255, 141, 161, 0.15);
            padding: 30px;
        }

        .description-title {
            font-size: 24px;
            color: #ff4d7a;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #ffdde4;
        }

        .description-content {
            line-height: 1.8;
            color: #555;
            font-size: 16px;
        }

        .description-content img {
            max-width: 100%;
            border-radius: 10px;
            margin: 15px 0;
        }

        /* 页脚 */
        .footer {
            background: linear-gradient(135deg, #343a40 0%, #23272b 100%);
            color: #fff;
            padding: 50px 0 30px;
            margin-top: 70px;
        }

        .footer-content {
            max-width: 1200px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 35px;
            padding: 0 20px;
        }

        .footer-column h3 {
            font-size: 20px;
            margin-bottom: 22px;
            padding-bottom: 12px;
            border-bottom: 2px solid #ff4d7a;
            color: #fff;
        }

        .footer-column ul {
            list-style: none;
        }

        .footer-column li {
            margin-bottom: 14px;
        }

        .footer-column a {
            color: #ddd;
            text-decoration: none;
            transition: all 0.3s;
            display: flex;
            align-items: center;
        }

        .footer-column a i {
            margin-right: 8px;
            color: #ff8da1;
        }

        .footer-column a:hover {
            color: #ff8da1;
            transform: translateX(5px);
        }

        .copyright {
            text-align: center;
            padding-top: 40px;
            margin-top: 40px;
            border-top: 1px solid #444;
            color: #aaa;
            font-size: 14px;
            max-width: 1200px;
            margin: 40px auto 0;
        }

        /* 加入购物车动画 */
        .cart-animation {
            position: fixed;
            width: 40px;
            height: 40px;
            background: #ff4d7a;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
            z-index: 10000;
            pointer-events: none;
            animation: cartFly 0.8s cubic-bezier(0.5, -0.5, 1, 1);
        }

        @keyframes cartFly {
            0% {
                transform: translate(0, 0);
                opacity: 1;
            }

        }

        /* 用户登录提示 */
        .login-prompt {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            z-index: 10000;
            text-align: center;
            max-width: 500px;
            width: 90%;
            display: none;
        }

        .login-prompt h3 {
            color: #ff4d7a;
            font-size: 24px;
            margin-bottom: 20px;
        }

        .login-prompt p {
            color: #666;
            margin-bottom: 25px;
            line-height: 1.6;
        }

        .login-actions {
            display: flex;
            gap: 15px;
            justify-content: center;
        }

        .login-btn {
            padding: 12px 30px;
            border-radius: 30px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .login-now {
            background: linear-gradient(135deg, #ff4d7a 0%, #ff8da1 100%);
            color: white;
            border: none;
        }

        .continue-shopping {
            background: white;
            border: 2px solid #ff4d7a;
            color: #ff4d7a;
        }

        .login-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.6);
            z-index: 9999;
            display: none;
        }

        /* 响应式设计 */
        @media (max-width: 992px) {
            .detail-content {
                flex-direction: column;
            }

            .product-gallery, .product-info {
                width: 100%;
            }

            .product-gallery {
                border-right: none;
                border-bottom: 1px solid #f0f0f0;
            }

            .footer-content {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .header-container {
                padding: 15px;
            }

            .nav-menu {
                width: 100%;
                margin-top: 15px;
                flex-wrap: wrap;
                justify-content: center;
            }

            .nav-menu li {
                padding: 10px 15px;
            }

            .action-buttons {
                flex-direction: column;
            }

            .main-image-container {
                height: 300px;
            }

            .login-actions {
                flex-direction: column;
            }
        }

        @media (max-width: 576px) {
            .footer-content {
                grid-template-columns: 1fr;
            }

            .sales-info {
                flex-direction: column;
                gap: 10px;
            }

            .thumbnail {
                width: 60px;
                height: 60px;
            }

            .user-info span {
                display: none;
            }
        }
    </style>
</head>
<body>
<!-- 顶部导航栏 -->
<div class="header-container">
    <div class="logo">
        <i class="fas fa-shopping-bag"></i>
        <span>百货购物平台</span>
    </div>
    <ul class="nav-menu">
        <li>
            <a href="index.html"><i class="fas fa-home"></i> 首页</a>
        </li>
        <li>
            <a href="cart item.html"><i class="fas fa-shopping-cart"></i> 购物车</a>
        </li>
        <li>
            <a href="checkout.html"><i class="fas fa-cash-register"></i> 结算</a>
        </li>
        <li>
            <a href="order.html"><i class="fas fa-file-invoice"></i> 我的订单</a>
        </li>
        <li>
            <a href="person_center.html"><i class="fas fa-user-circle"></i> 个人中心</a>
        </li>
        <li>
            <a href="customer_service.html"><i class="fas fa-headset"></i> 官方客服</a>
        </li>
    </ul>

    <div class="user-info" id="userInfo">
        <i class="fas fa-user"></i>
        <span id="username">未登录</span>
    </div>
</div>

<!-- 用户登录提示 -->
<div class="login-overlay" id="loginOverlay"></div>
<div class="login-prompt" id="loginPrompt">
    <h3></h3>
    <p>您需要登录后才能将商品加入购物车。登录后，您可以享受更多会员权益！</p>
    <div class="login-actions">
        <button class="login-btn login-now" id="loginNowBtn">立即登录</button>
        <button class="login-btn continue-shopping" id="continueShoppingBtn">继续购物</button>
    </div>
</div>

<!-- 商品详情容器 -->
<div class="product-detail-container">
    <div class="detail-content">
        <!-- 商品图片区域 -->
        <div class="product-gallery">
            <div class="main-image-container">
                <img src="" alt="商品主图" class="main-image" id="mainImage">
            </div>
            <div class="thumbnail-container" id="thumbnailContainer">
                <!-- 缩略图将通过JS动态生成 -->
            </div>
        </div>

        <!-- 商品信息区域 -->
        <div class="product-info">
            <h1 class="product-title" id="productTitle">加载中...</h1>

            <div class="price-container">
                <div class="price-label">售价</div>
                <div>
                    <span class="current-price" id="currentPrice">¥0.00</span>
                </div>

                <div class="sales-info">
                    <div class="info-item">库存：<span id="stock">0</span>件</div>
                </div>
            </div>

            <div class="quantity-container">
                <div class="quantity-title">数量</div>
                <div class="quantity-control">
                    <button class="quantity-btn" id="decreaseBtn" disabled>-</button>
                    <input type="text" class="quantity-input" id="quantity" value="1">
                    <button class="quantity-btn" id="increaseBtn">+</button>
                    <div class="stock-info">库存<span id="stockNum">0</span>件</div>
                </div>
            </div>

            <div class="action-buttons">
                <button class="cart-btn" id="addToCartBtn">
                    <i class="fas fa-shopping-cart"></i> 加入购物车
                </button>
                <button class="buy-btn" id="buyNowBtn">
                    <i class="fas fa-bolt"></i> 立即购买
                </button>
            </div>
        </div>
    </div>

    <!-- 商品详情描述 -->
    <div class="product-description">
        <h2 class="description-title">商品详情</h2>
        <div class="description-content" id="descriptionContent">
            <!-- 商品描述将通过JS动态生成 -->
        </div>
    </div>
</div>

<script>
    // 确保在LayUI加载完成后执行代码
    layui.use(['layer'], function() {
        var layer = layui.layer;
        window.layer = layer; // 将layer设置为全局变量

        // 全局设置AJAX请求携带凭证
        $.ajaxSetup({
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true
        });

        // 初始化用户信息
        function initUserInfo() {
            // 从sessionStorage中获取用户信息
            const userData = sessionStorage.getItem('user');
            console.log('用户信息:', userData)
            if (userData) {
                try {
                    const user = JSON.parse(userData);
                    console.log('转为json的user:',user);
                    if (user && user.userId) {
                        $('#username').text(user.userName || '已登录');
                        return true;
                    }
                } catch (e) {
                    console.error('解析用户信息失败', e);
                }
            }
            $('#username').text('未登录');
            return false;
        }

        // todo:获取当前登录用户ID，从会话中获取，前端会话存储了用户id
        function getCurrentUserId() {
           // const user = sessionStorage.getItem('user');
            const user = JSON.parse(sessionStorage.getItem('user'));
            // if (userData) {
            // if (userData){
            //     try {
            //         const user = JSON.parse(userData);
            //         if (user && user.userId) {
            //             return user.userId;
            //         }
            //     } catch (e) {
            //         console.error('解析用户信息失败', e);
            //     }
            // }
            if (user){
                try {
                    // const user = JSON.parse(user);
                    if (user && user.userId) {
                        console.log('当前用户ID:', user.userId);
                        return user.userId;
                    }
                } catch (e) {
                    console.error('解析用户信息失败', e);
                }
            }
            return null;
        }

        // 显示登录提示
        function showLoginPrompt() {
            $('#loginOverlay').fadeIn();
            $('#loginPrompt').fadeIn();
        }

        // 隐藏登录提示
        function hideLoginPrompt() {
            $('#loginOverlay').fadeOut();
            $('#loginPrompt').fadeOut();
        }

        // 获取URL中的商品ID
        function getProductIdFromUrl() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('id');
        }

        // 获取后端基础URL - 解决跨域问题
        function getBackendBaseUrl() {
            // 根据当前环境确定后端URL
            if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
                return 'http://localhost:8080';
            }
            // 生产环境使用相同域名
            return window.location.origin;
        }

        // 加载商品详情数据
        function loadProductDetail(productId) {

            if (!productId) {
                console.error('商品ID未提供');
                return;
            }

            $.ajax({
                url: getBackendBaseUrl() + '/product/detailed',
                method: 'GET',
                xhrFields: {
                    withCredentials: true          //允许携带凭证
                },
                data: { id: productId },
                success: function(response) {
                    // 检查响应状态码
                    if (response.code === 200) {
                        // 获取商品详情数据
                        const productDetail = response.data;
                        renderProductDetail(productDetail);
                    } else {
                        console.error('获取商品详情失败：', response.message);
                        layer.msg('获取商品详情失败: ' + response.message, {icon: 2, time: 3000});
                    }
                },
                error: function(error) {
                    console.error('AJAX请求错误：', error);
                    layer.msg('获取商品详情失败，请重试', {icon: 2, time: 3000});
                }
            });
        }

        // 渲染商品详情
        function renderProductDetail(productDetail) {
            const product = productDetail.product;
            const masterPic = productDetail.masterPic;
            const slavePics = productDetail.slavePics || [];

            // 设置商品标题
            $('#productTitle').text(product.title);

            // 设置商品价格
            $('#currentPrice').text('¥' + product.price.toFixed(2));

            // 设置库存信息
            $('#stock').text(product.stock);
            $('#stockNum').text(product.stock);

            // 设置商品描述
            if (product.note) {
                $('#descriptionContent').html(`<p>${product.note}</p>`);
            } else {
                $('#descriptionContent').html('<p>暂无商品描述</p>');
            }

            // 设置商品图片
            const mainImage = $('#mainImage');
            const thumbnailContainer = $('#thumbnailContainer');

            // 先清空缩略图容器
            thumbnailContainer.empty();

            // 如果有主图
            if (masterPic) {
                mainImage.attr('src', masterPic.url);
                mainImage.attr('alt', masterPic.title || product.title);

                // 添加主图缩略图
                const masterThumbnail = createThumbnail(masterPic.url, masterPic.title, true);
                thumbnailContainer.append(masterThumbnail);
            } else {
                // 使用默认图片
                mainImage.attr('src', 'https://via.placeholder.com/600x600?text=商品图片');
            }

            // 添加从图缩略图
            slavePics.forEach((pic, index) => {
                const thumbnail = createThumbnail(pic.url, pic.title, false);
                thumbnailContainer.append(thumbnail);
            });

            // 初始化数量控制器
            updateQuantityControls();
        }

        // 创建缩略图元素
        function createThumbnail(url, title, isMaster) {
            const thumbnail = $(`
                <div class="thumbnail ${isMaster ? 'active' : ''}">
                    <img src="${url}" alt="${title || '商品图片'}">
                </div>
            `);

            // 绑定点击事件
            thumbnail.on('click', function() {
                // 更新主图
                $('#mainImage').attr('src', url);

                // 更新缩略图选中状态
                $('.thumbnail').removeClass('active');
                $(this).addClass('active');
            });

            return thumbnail;
        }

        // 数量控制
        function updateQuantityControls() {
            const quantity = parseInt($('#quantity').val()) || 1;
            const stock = parseInt($('#stockNum').text()) || 0;

            $('#decreaseBtn').prop('disabled', quantity <= 1);
            $('#increaseBtn').prop('disabled', quantity >= stock);
        }

        // 加入购物车动画
        function createCartAnimation(startX, startY) {
            const cartIcon = $('.fa-shopping-cart')[0];
            const cartRect = cartIcon.getBoundingClientRect();

            const animation = $('<div class="cart-animation"><i class="fas fa-plus"></i></div>');
            animation.css({
                left: startX + 'px',
                top: startY + 'px'
            });

            animation.css('--endX', (cartRect.left - startX) + 'px');
            animation.css('--endY', (cartRect.top - startY) + 'px');

            $('body').append(animation);

            setTimeout(() => {
                animation.remove();
            }, 800);
        }

        // 初始化页面
        $(document).ready(function() {
            // 初始化用户信息
            initUserInfo();

            // 获取商品ID并加载详情
            const productId = getProductIdFromUrl();
            if (productId) {
                loadProductDetail(productId);
            } else {
                layer.msg('商品ID无效', {icon: 2, time: 2000});
            }

            // 数量控制事件
            $('#decreaseBtn').on('click', function() {
                let quantity = parseInt($('#quantity').val()) || 1;
                if (quantity > 1) {
                    $('#quantity').val(quantity - 1);
                    updateQuantityControls();
                }
            });

            $('#increaseBtn').on('click', function() {
                let quantity = parseInt($('#quantity').val()) || 1;
                const stock = parseInt($('#stockNum').text()) || 0;
                if (quantity < stock) {
                    $('#quantity').val(quantity + 1);
                    updateQuantityControls();
                }
            });

            $('#quantity').on('input', function() {
                let quantity = parseInt($(this).val()) || 1;
                const stock = parseInt($('#stockNum').text()) || 0;

                if (quantity < 1) quantity = 1;
                if (quantity > stock) quantity = stock;

                $(this).val(quantity);
                updateQuantityControls();
            });

            // 加入购物车功能
            $('#addToCartBtn').on('click', async function() {
                const btnRect = this.getBoundingClientRect();
                const startX = btnRect.left + btnRect.width / 2;
                const startY = btnRect.top + btnRect.height / 2;

                // 创建动画效果
                createCartAnimation(startX, startY);

                try {
                    const userId = getCurrentUserId();
                    if (!userId) {
                        showLoginPrompt();
                        return;
                    }

                    const productId = getProductIdFromUrl();
                    if (!productId) {
                        throw new Error('商品信息无效');
                    }

                    const quantity = parseInt($('#quantity').val()) || 1;

                    // 发送JSON格式数据
                    $.ajax({
                        url: getBackendBaseUrl() + `/cart/add`,
                        method: 'POST',
                        contentType: 'application/json',
                        headers:{
                            userId: userId
                        },
                        xhrFields: {
                            withCredentials: true          //允许携带凭证
                        },
                        data: JSON.stringify({
                            productId: parseInt(productId),
                            quantity: quantity
                        }),
                        success: function(response) {
                            if (response.code === 200) {
                                layer.msg('商品已成功加入购物车', {icon: 1, time: 2000});
                                loadProductDetail(productId);
                            } else {
                                throw new Error(response.message || '加入购物车失败');
                            }
                        },
                        error: function(error) {
                            console.error('加入购物车失败:', error);
                            layer.msg('加入购物车失败: ' + (error.responseJSON?.message || '网络错误'), {icon: 2, time: 2000});
                        }
                    });

                } catch (error) {
                    console.error('加入购物车失败:', error);
                    layer.msg(error.message || '加入购物车失败', {icon: 2, time: 2000});
                }
            });

            $('#buyNowBtn').on('click', function() {
                // 检查用户是否登录
                const userId = getCurrentUserId();
                if (!userId) {
                    showLoginPrompt();
                    return;
                }
                layer.msg('跳转到结算页面', {icon: 1, time: 1500});

            });

            // 用户登录按钮事件
            $('#userInfo').on('click', function() {
                const userId = getCurrentUserId();
                if (!userId) {
                    showLoginPrompt();
                } else {
                    // 跳转到个人中心
                    window.location.href = 'person_center.html';
                }
            });

            // 登录提示按钮事件
            $('#loginNowBtn').on('click', function() {
                window.location.href = 'longin.html';
            });

            $('#continueShoppingBtn').on('click', function() {
                hideLoginPrompt();
            });

            // 点击遮罩层关闭登录提示
            $('#loginOverlay').on('click', function() {
                hideLoginPrompt();
            });
        });
    });
</script>
</body>
</html>